package wj.tree;

import wj.WJValue;

public class CharAtStringNode implements WJNode{

	private WJNode stringNode;
	private WJNode indexExpression;
	
	public CharAtStringNode(WJNode stringNode, WJNode indexExpression){
		this.stringNode = stringNode;
		this.indexExpression = indexExpression;
	}
	
	@Override
	public WJValue evaluate() {
		try{
			String string = stringNode.evaluate().toString();
			int index = indexExpression.evaluate().toInt();
			
			if(index >= string.length())
				throw new RuntimeException("The string "+string+"'s maximum index is "+(string.length()-1)+". You tried to access index "+index);
			
			return new WJValue(string.charAt(index));
		}catch(Exception e){
			return WJValue.NULL;
		}
	}

	
}
